package com.hfuuwzy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hfuuwzy.commom.Constants;
import com.hfuuwzy.controller.dto.UserDTO;
import com.hfuuwzy.controller.dto.UserPasswordDTO;
import com.hfuuwzy.entity.Course;
import com.hfuuwzy.entity.Menu;
import com.hfuuwzy.entity.User;
import com.hfuuwzy.exception.ServiceException;
import com.hfuuwzy.mapper.RoleMapper;
import com.hfuuwzy.mapper.RoleMenuMapper;
import com.hfuuwzy.mapper.UserMapper;
import com.hfuuwzy.service.MenuService;
import com.hfuuwzy.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hfuuwzy.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wzy
 * @since 2023-03-25 00:00:00
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    // 利用Hutool工具打印异常
    private static final Log LOG = Log.get();

    @Autowired
    private RoleMapper roleMapper;

    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private MenuService menuService;

    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }

    @Override
    public UserDTO login(UserDTO userDTO) {

        // 只校验一个
//        User one = getOne(queryWrapper);
//        return one != null;
        // 第一种方式
//        List<User> list = list(queryWrapper);
//        return list.size() != 0;

        // 第二种方式
        User one = getUserInfo(userDTO);
        if (one != null) {
            BeanUtil.copyProperties(one, userDTO, true); // 忽略大小写 ,把one对象复制给userDTO对象
            // 设置token
            String token = TokenUtils.getToken(one.getId().toString(), one.getPassword());
            userDTO.setToken(token);

            // 查出用户管理的所有菜单id集合
            String roleFlag = one.getRole(); // ROLE_ADMIN
            // 设置用户的菜单列表
            userDTO.setMenus(getRoleMenus(roleFlag));
            return userDTO;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }

    @Override
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true); // 忽略大小写
            save(one); // 吧copy完之后的用户存储到数据库
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }

    @Override
    public void updatePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }
    }

    @Override
    public Page<User> findPage(Page<User> userPage, String username, String email, String address) {
        return userMapper.findPage(userPage, username, email, address);
    }

    @Override
    public List lookStuCourse() {
        return userMapper.getStuScore();
    }

    /**
     * 获取当前角色的菜单列表
     *
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag) {
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        // 当前用户的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);
        // 查出系统所有菜单
        List<Menu> menus = menuService.findMenus("");
        // new一个筛选完成之后的list
        ArrayList<Menu> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            // removeIf 移除children里面不在 menuIds集合中的元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }

}
